package datastructure.sort;

import java.util.Arrays;
import java.util.Random;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/30 8:25
 * @description:
 */
public class QuickSort {
    public static void quickSort(int[] nums, int l, int r) {
        if (r <= l) return;
        int midPos = partition(nums, l, r);//分区
        quickSort(nums, l, midPos - 1);//排序左边
        quickSort(nums, midPos + 1, r);//排序右边

    }

    public static int partition(int[] nums, int l, int r) {
        int mid = nums[l];//第一个元素为分区元素
        while (l < r) {
            while (nums[l] < mid) {//左边找不合顺序的
                l++;
            }
            while (nums[r] > mid) {//右边找不合顺序的
                r--;
            }
            if (l < r) {//交换不合顺序的
                swap(nums, l, r);
            }
        }
        return l;
    }

    public static void swap(int[] nums, int x, int y) {
        int temp = nums[x];
        nums[x] = nums[y];
        nums[y] = temp;
    }

    public static void shuffle(int[] nums) {
        Random r = new Random();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            int j = i + r.nextInt(n - i);
            swap(nums, i, j);
        }
    }


    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 4, 6, -1, -4, -10};
        shuffle(nums);
        System.out.println(Arrays.toString(nums));
        quickSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }
}
